package core

type CollectionMap struct {
	Keys   []int64
	Values []map[string]interface{}
}

func NewCollectionMap() *CollectionMap {
	return &CollectionMap{
		Keys:   make([]int64, 0),
		Values: make([]map[string]interface{}, 0),
	}
}

func (t *CollectionMap) Put(key int64, value map[string]interface{}) {
	pos, has := t.indexOf(key)
	//fmt.Println(pos, has)
	if has {
		t.Values[pos] = value
		return
	}
	//放到前面
	rear := append([]int64{}, t.Keys[pos:]...)
	t.Keys = append(t.Keys[0:pos], key)
	t.Keys = append(t.Keys, rear...)

	rear_v := append([]map[string]interface{}{}, t.Values[pos:]...)
	t.Values = append(t.Values[0:pos], value)
	t.Values = append(t.Values, rear_v...)
}

func (t *CollectionMap) Delete(key int64) bool {
	pos, has := t.indexOf(key)
	if has {
		t.Keys = append(t.Keys[:pos], t.Keys[pos+1:]...)
		t.Values = append(t.Values[:pos], t.Values[pos+1:]...)
		return true
	}
	return false
}

func (t *CollectionMap) Get(key int64) map[string]interface{} {
	pos, has := t.indexOf(key)
	if has {
		return t.Values[pos]
	}
	return nil
}

func (t *CollectionMap) indexOf(key int64) (pos int, found bool) {
	start := 0
	end := len(t.Values) - 1
	var mid int
	for start <= end {
		mid = start + (end-start)/2
		if t.Keys[mid] < key {
			start = mid + 1
		} else if t.Keys[mid] > key {
			end = mid - 1
		} else {
			found = true
			pos = mid
			return
		}
	}
	pos = start
	return
}
